package sk.hackcraft.multibox.android.net;

import java.io.IOException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;

import android.os.Handler;

public class HttpInterface
{
	private Handler handler;
	private final BlockingQueue<Request> requests = new LinkedBlockingQueue<Request>();
	private NetThread netThread = new NetThread();
	
	private String address;
	private long token;
	private boolean hasToken = false;
	
	public HttpInterface(Handler handler)
	{
		this.handler = handler;
		
		netThread.start();
	}
	
	protected void finalize() throws Throwable
	{
		super.finalize();
		
		netThread.interrupt();
	}
	
	public boolean hasToken()
	{
		return hasToken;
	}
	
	public void setToken(long token)
	{
		hasToken = true;
	}
	
	public void run(Request request)
	{
		requests.offer(request);
	}
	
	private class NetThread extends Thread
	{
		private HttpClient httpClient = new DefaultHttpClient();
		private HttpPost httpPost = new HttpPost("http://localhost:8080/");
		
		public void run()
		{
			while (!isInterrupted())
			{
				try
				{
					final Request request = requests.take();
					
					request.prepare(httpClient, httpPost, token);
					
					try
					{
						request.run();
						
						handler.post(new Runnable()
							{
								@Override
								public void run()
								{
									request.getCallback().run();
								}
							}
						);
					}
					catch (IOException e)
					{
						
					}
					catch (JSONException e)
					{
						
					}
				}
				catch (InterruptedException e)
				{
					interrupt();
				}
			}
		}
	}
}
